package com.goodwill.androidtest.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author guoxiaojun
 * @date 2019/11/8
 * @desc 文件操作的工具类
 */
public class FileUtils {

    /**
     * 读取assets目录下的文件
     *
     * @param context  上下文对象
     * @param fileName 文件名
     * @return String
     */
    public static String readAssetsFile(Context context, String fileName) {
        if (context == null || TextUtils.isEmpty(fileName)) return "";
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            AssetManager assetManager = context.getAssets();
            bufferedReader = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(bufferedReader);
        }
        return stringBuilder.toString();
    }

    /**
     * 自动更新下载文件
     *
     * @param url 文件下载地址
     * @param downFilePath 文件下载到sd卡目录
     * @param downFileName  下载文件名
     * @author guoxiaojun
     */
    public static void fileDownload(String url, String downFilePath,
                                    String downFileName) {
        try {
            File file = new File(downFilePath, downFileName);
            if (file.exists()) {
                file.delete();
            }
            URL myURl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) myURl.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty(
                    "Accept",
                    "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            conn.setRequestProperty("Accept-Language", "zh-CN");
            conn.setRequestProperty("Referer", url);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.connect();
            InputStream is = conn.getInputStream();
            int fileSize = conn.getContentLength();
            if (fileSize <= 0) {
                throw new RuntimeException("无法获取文件");
            } else if (is == null) {
                throw new RuntimeException("InputStream is null");
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int downloadSize = 0;
            do {
                int numread = is.read(buf);
                if (numread == -1) {
                    break;
                }
                fileOutputStream.write(buf, 0, numread);
                downloadSize += numread;
            } while (downloadSize < fileSize);

            fileOutputStream.flush();
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Close closable object and wrap {@link IOException} with {@link
     * RuntimeException}
     *
     * @param closeable closeable object
     */
    public static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                Log.i("IOException occurred. ", e.getMessage());
            }
        }
    }
}
